<script setup lang="ts">
import { ArrowRight } from '@element-plus/icons-vue'
import { getCategoryChildrenByIdApi, getMoreCategoryApi } from '@/apis/category'
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import type { GoodsType } from '@/apis/components/goodsType'
import type { CategoryTwoByIdType, PostMoreGoodsType } from '@/apis/components/categoryType'
import GoodsItem from '../Home/components/GoodsItem.vue'

const route = useRoute()

// 获取二级分类
const categoryChildrenByIdList = ref<CategoryTwoByIdType>()
// 获取基本列表数据
const goods = ref<GoodsType[]>()
const reqData = ref<PostMoreGoodsType>({
  categoryId: route.path.slice(22),
  page: 1,
  pageSize: 20,
  sortField: 'publishTime',
})

// 获取二级分类数据
const getCategoryChildrenById = async () => {
  const id = route.path.slice(22)
  const res = await getCategoryChildrenByIdApi(id)
  categoryChildrenByIdList.value = res.data.result
}
// 获取基本列表数据
const getGoodsList = async () => {
  const res = await getMoreCategoryApi(reqData.value)
  goods.value = res.data.result.items
}
onMounted(() => {
  getCategoryChildrenById()
  getGoodsList()
})

watch(
  () => route.path,
  () => getCategoryChildrenById(),
)

// 加载更多
const disabled = ref(false)
const load = async () => {
  // 获取下一页的数据
  reqData.value.page++
  const res = await getMoreCategoryApi(reqData.value)
  goods.value = goods.value?.concat(res.data.result.items)
  // 加载完毕 停止监听
  if (res.data.result.items.length < 1) {
    disabled.value = true
  }
}
</script>

<template>
  <div class="breadcrumb-box">
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: `/category/${categoryChildrenByIdList?.parentId}` }">
        {{ categoryChildrenByIdList?.parentName }}
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{ categoryChildrenByIdList?.name }}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div class="allGoods">
    <p>全部商品</p>
    <ul v-infinite-scroll="load" :infinite-scroll-disabled="disabled">
      <li v-for="item in goods" :key="item.id">
        <GoodsItem :goods="item"></GoodsItem>
      </li>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
.breadcrumb-box {
  width: 1100px;
  height: 30px;
  margin-left: 20px;
  .el-breadcrumb {
    font-size: 18px;
  }
}
.allGoods {
  width: 1100px;
  margin: 0 auto;
  text-align: center;
  p {
    font-size: 20px;
    font-weight: 700;
  }
  ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    li {
      list-style: none;
      margin-top: 20px;
    }
  }
}
</style>
